package com.blinddate.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.blinddate.context.BaseContext;
import com.blinddate.mapper.UserInfMapper;
import com.blinddate.mapper.UserMapper;
import com.blinddate.pojo.entity.GuangGao;
import com.blinddate.pojo.entity.User;
import com.blinddate.pojo.entity.UserInf;
import com.blinddate.pojo.result.Result;
import com.blinddate.properties.AliOssProperties;
import com.blinddate.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 文件上传下载
 */
@RestController
@RequestMapping("/user/common")
@Slf4j
@Api(tags = "通用功能")
public class CommonController {

    @Autowired
    private AliOssUtil aliOssUtil;
    @Autowired
    private AliOssProperties aliOssProperties;
    @Autowired
    private UserInfMapper userInfMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @PostMapping("/upload")
    @ApiOperation("上传用户照片")
    public Result upload(MultipartFile []file){//进行文件传输
       log.info(file.toString());
        List<String> filePaths=new ArrayList<>();
        String key="user"+BaseContext.getCurrentId();
       //动态获取文件后缀
        for (MultipartFile multipartFile : file) {
            String originalFilename = multipartFile.getOriginalFilename();
            String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
            //根据uuid设置文件名
            String s = UUID.randomUUID().toString()+substring;
            try {
                String filePath = aliOssUtil.upload(multipartFile.getBytes(), s);
                filePaths.add(filePath);
            } catch (IOException e) {
                throw new RuntimeException("上传文件模块有异常请查看CommonController类:"+e.getMessage());
            }
        }
//        String originalFilename = file.getOriginalFilename();
//        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
//        //根据uuid设置文件名
//        String s = UUID.randomUUID().toString()+substring;
//        try {
//            String filePath = aliOssUtil.upload(file.getBytes(), s);
//            return Result.success(filePath);
//        } catch (IOException e) {
//            throw new RuntimeException("上传文件模块有异常请查看CommonController类:"+e.getMessage());
//        }
//        文件名
        List<String> list= (List<String>) redisTemplate.opsForValue().get(key);
        if(list==null){
            list=new ArrayList<>();
        }
        list.addAll(filePaths);
        redisTemplate.opsForValue().set(key,list);
        log.info("{}",list);
        return Result.success(filePaths);
    }
    @PostMapping("/upload_guanggao")
    @ApiOperation("上传广告照片（不会删除）")
    public Result GGupload(MultipartFile []file){//进行文件传输
        log.info(file.toString());
        List<String> filePaths=new ArrayList<>();
        //动态获取文件后缀
        for (MultipartFile multipartFile : file) {
            String originalFilename = multipartFile.getOriginalFilename();
            String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
            //根据uuid设置文件名
            String s = UUID.randomUUID().toString()+substring;
            try {
                String filePath = aliOssUtil.upload(multipartFile.getBytes(), s);
                filePaths.add(filePath);
            } catch (IOException e) {
                throw new RuntimeException("上传文件模块有异常请查看CommonController类:"+e.getMessage());
            }
        }
        return Result.success(filePaths);
    }

//    @GetMapping("/download")
//    public void download(String name, HttpServletResponse response){
//        //读取文件
//        try {
//            FileInputStream fileInputStream=new FileInputStream(basePath+name);
//            ServletOutputStream outputStream = response.getOutputStream(); //输出文件
//            response.setContentType("imag/jpeg");
//            int len=0;
//            byte[] bytes = new byte[1024];
//            while ((len=fileInputStream.read(bytes))!=-1){ //进行读取read返回的是读取到的多少，没有读取则返回-1
//                outputStream.write(bytes,0,len);
//                outputStream.flush();//刷新
//            }
//            outputStream.close();
//            fileInputStream.close();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        //输出文件内容
//    }
    @GetMapping("/pdf")
    @ApiOperation("获取用户的pdf信息" )
    public Result<String> pdf(Long userid) throws IOException {
        User user=userMapper.selectById(userid);
        if(user.getPdfPath()!=null&&user.getPdfPath()!=""){
            log.info("{}",user.getPdfPath());
            return Result.success(user.getPdfPath());
        }else {
            log.info("生成用户id为：{}的pdf文件",userid);
            LambdaQueryWrapper<UserInf> lqw=new LambdaQueryWrapper<UserInf>();
            lqw.eq(UserInf::getUserId,userid);
            UserInf userInf=userInfMapper.selectOne(lqw);
            String s = userid.toString()+".pdf";
            String pdfpath=aliOssUtil.pdf(userInf,s);
            user.setPdfPath(pdfpath);
            userMapper.updateById(user);
            return Result.success(pdfpath);
        }

    }
    @GetMapping("/get_guanggao")
    @ApiOperation("获取广告url" )
    public Result guanggao() throws IOException {
        List<String> urls= (List<String>) redisTemplate.opsForValue().get("guanggao");
            return Result.success(urls);
        }

    @PostMapping("/update_guanggao")
    @ApiOperation("修改广告url" )
    public Result<String> guanggao(@RequestBody GuangGao guangGao) throws IOException {
        log.info("d{}",guangGao.getUrls());
        redisTemplate.opsForValue().set("guanggao",guangGao.getUrls());
        return Result.success();
    }



}

